#include <stdio.h>
#include <string.h>
#include <malloc.h>
#define MAX_WORD (100)

typedef struct tnode
{
    char ch;                                //  字符
    int cnt;                                //  出现次数
    struct tnode *lchild;                   //  左指针
    struct tnode *rchild;                   //  右指针
}BSTNode;                                   //  结点类型

/*-----------------采用递归方式向二叉排序树bst中插入一个字符----------------*/
static void create_bst(BSTNode *&bt, char ch)               // 指针的引用
{
    if(bt == NULL)                                          // bt为空,则建立一个新结点
    {
        bt = (BSTNode *)malloc(sizeof(BSTNode));
        bt->ch = ch;
        bt->cnt = 1;
        bt->lchild = bt->rchild = NULL;
    }
    else if(ch == bt->ch)
        bt->cnt++;
    else if(ch < bt->ch)
        create_bst(bt->lchild, ch);
    else
        create_bst(bt->rchild, ch);
}

/*-----------------中序遍历二叉排序树bst----------------*/
static void inorder(BSTNode *bt)
{
    if(bt != NULL)
    {
        inorder(bt->lchild);                    //  中序遍历左子树
        printf("  %c(%d)\n", bt->ch, bt->cnt); //  访问根结点
        inorder(bt->rchild);                    //  中序遍历右子树
    }
}

/*-----------------销毁二叉排序树bst----------------*/
static void destroy_bst(BSTNode *bt)
{
    if(bt != NULL)
    {
        destroy_bst(bt->lchild);
        destroy_bst(bt->rchild);
        free(bt);
    }
}

int main(int argc, char *argv[])
{
    BSTNode *bt = NULL;
    int i = 0;
    char str[MAX_WORD];

    printf("输入字符串:");
    gets(str);
    while(str[i] != '\0')
    {
        create_bst(bt, str[i]);
        i++;
    }
    printf("字符及出现次数:\n");
    inorder(bt);
    printf("\n");
    destroy_bst(bt);

    return 0;
}
